package com.polaris.live.popup

import android.content.Context
import android.text.Editable
import android.widget.LinearLayout
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.FormatUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupFeedBackBinding
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.FeedbackBean
import com.polaris.live.translation.R.string

/**
 * 反馈与建议弹窗
 *
 * @author Created by 半仙 on 2023/11/2/002 17:45
 */
class FeedBackPopup(
    context: Context,
    private val viewModel: BaseViewModel
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupFeedBackBinding

    override fun getImplLayoutId(): Int {
        return R.layout.popup_feed_back
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupFeedBackBinding.bind(popupImplView)
        mBinding.etFeedback.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                mBinding.tvTextLength.text = "${s?.length}/1500"
            }
        })
        mBinding.tvCommitFeedback.setOnSingleClickListener {
            val feedback = mBinding.etFeedback.text.toString().trim()
            val email = mBinding.etEmail.text.toString().trim()
            if (feedback.isEmpty()) {
                ToastGravity.showGravity(string.please_input_feedback)
                return@setOnSingleClickListener
            } else if (email.isEmpty()) {
                ToastGravity.showGravity(string.please_input_email)
                return@setOnSingleClickListener
            } else if (!FormatUtils.isEmail(email)) {
                ToastGravity.showGravity(string.please_input_correct_email)
                return@setOnSingleClickListener
            }

            viewModel.requestLoading({ userService.feedback(FeedbackBean(content = feedback, email = email)) }, {
                ToastGravity.showGravity(context.getString(string.feedback_success))
            }, { ToastGravity.showGravity(it.errorMsg) })

            dismiss()
        }

        val navigationBarHeight = NavigationBarUtils.getNavigationBarHeight(context)
        val layout = mBinding.llView.layoutParams as LinearLayout.LayoutParams
        layout.bottomMargin = navigationBarHeight
        mBinding.llView.layoutParams = layout
    }
}